﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using MailingSystemWcfServiceRole.Entities;

namespace MailingSystemWcfServiceRole.Services
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ContactService" in code, svc and config file together.
    public class ContactService : IContactService
    {
        public bool AddContact(Contact c)
        {
            string connString = ConfigurationManager.ConnectionStrings["CalvinSQLDB"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand comm = new SqlCommand("INSERT into mailingList values(@studId, @studName, @school, @email, @contactNo, 1, 1)", conn);
            comm.Parameters.AddWithValue("@studId", c.StudentID);
            comm.Parameters.AddWithValue("@studName", c.StudentName);
            comm.Parameters.AddWithValue("@school", c.School);
            comm.Parameters.AddWithValue("@email", c.Email);

            bool isAddingSuccessful = false;

            if (!Contact.ContactExists(c.StudentID))
            {
                try
                {
                    if (comm.ExecuteNonQuery() == 1)
                    {
                        isAddingSuccessful = true;
                    }
                }
                catch (Exception e)
                {
                    //do nothing
                }
                finally
                {
                    conn.Close();
                }
            }
            return isAddingSuccessful;
        }

        public static bool ContactExists(string studId)
        {
            //string connString = ConfigurationManager.ConnectionStrings["CalvinSQLDB"].ConnectionString;
            //SqlConnection conn = new SqlConnection(connString);
            //SqlCommand comm = new SqlCommand("SELECT StudentID from mailingList WHERE StudentID = @studId", conn);
            //comm.Parameters.AddWithValue("@studId", studId);

            //bool exists = false;

            //try
            //{
            //    SqlDataReader rdr = comm.ExecuteReader();
            //    if (!rdr.Read())
            //    {
            //        exists = true;
            //    }
            //}
            //catch (Exception e)
            //{
            //    //do nothing
            //}
            //finally
            //{
            //    conn.Close();
            //}

            return Contact.ContactExists(studId);
        }

        //public static bool (string )
    }
}
